package com.crazydream.wechat.system.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.crazydream.wechat.common.dao.BaseDAO;
import com.crazydream.wechat.common.utils.QueryParameters;
import com.crazydream.wechat.common.vo.PageVo;
import com.crazydream.wechat.system.model.User;

@Service("userService")
public class UserService {
	
	@Autowired
	@Qualifier("dao")
	private BaseDAO dao;

	/**
	 * 验证用户是否存在
	 * @param username
	 * @return
	 */
	@Transactional
	public boolean checkUser(String username) {
		int count = dao.findRowCount(User.CHECK_USER, QueryParameters.with("username", username).parameters());
		boolean flag = false;
		if (count <= 0)
			flag = true;
		return flag;
	}

	/**
	 * 根据用户名查询用户
	 * @param username
	 * @return
	 */
	@Transactional
	public List<User> findByUserName(String username) {
		return dao.findWithNamedQuery(User.QUERY_BY_USER_NAME, QueryParameters.with("username", username).parameters());
	}

	/**
	 * 分页查询列表
	 * @param page
	 * @return
	 */
	@Transactional
	public PageVo<User> findForPageList(PageVo<User> page) {
		return page;
	}
	
	/**
	 * 根据ID查询用户
	 * @param user
	 * @return
	 */
	@Transactional
	public User findById(User user) {
		return dao.find(User.class, user.getId());
	}
	
	/**
	 * 修改用户信息，不修改密码
	 * @param user
	 */
	@Transactional
	public void LoginForUpdate(User user) {
		this.dao.update(user);
	}

	/**
	 * 修改用户信息，修改密码
	 * @param user
	 */
	@Transactional
	public void modify(User user) {
		String pwd = user.getPassword();
		if (pwd.length() < 32) {
			String newpwd = new Md5PasswordEncoder().encodePassword(pwd, user
					.getUsername());
			user.setPassword(newpwd);
		}
		dao.update(user);
	}

	/**
	 * 根据ID删除用户
	 * @param user
	 */
	@Transactional
	public void removeById(User user) {
		dao.delete(User.class, user.getId());
	}

	/**
	 * 创建用户
	 * @param user
	 * @return
	 */
	@Transactional
	public User save(User user) {
		user.setPassword(new Md5PasswordEncoder().encodePassword(user.getPassword(), user.getUsername()));
		return dao.create(user);
	}
}
